<?php
HBase::using('Backend.Robot.*');

class HModulesInstances {
	function getInstanceById($id) {
		$a = HSql::doQuery("SELECT id, module_id, view_file, friendly_name FROM portal_modules_instances WHERE id = '$id'");
		if (count($a) == 0) return null;
		else return $a;
	}
	
	function getViewFileById($id) {
		$a = HSql::fetch2Array(HSql::doQuery("SELECT id, view_file, friendly_name FROM portal_modules_instances WHERE id = '$id'"));		
		if (count($a) == 0) return 'index.php';
		else return $a[0]['view_file'];
	}
	
	function getControlKeyById($id) {
		return HSql::getFieldById("portal_modules_instances","control_key",$id);		
	}
	
	function getModuleIdByInstanceId($instance_id) {
		$a = HSql::fetch2Array(HSql::getData('portal_modules_instances',"WHERE id = '$instance_id'"));
		return $a[0]['module_id'];
	}
	
	function getViewFileByModuleIdAndControlKey($mid, $ctl) {
		$a = HSql::fetch2Array(HSql::getData('portal_modules_instances',"WHERE module_id = '$mid' AND control_key = '$ctl'"));
		return $a[0]['view_file'];
	}
	
	function getPaged($page, $size, $mid) {
		$offset = ($page - 1) * $size;
		$a = HSql::fetch2Array(HSql::getData("portal_modules_instances","WHERE module_id = '$mid' LIMIT ".$offset.",".$size));
		return $a;
	}

	function insert($name, $mid) {	
		try {	
			// Insert into database			
			$view_file = HModules::getModuleNameByModuleId($mid).'_'.$name.'.php';
			HSql::doQuery("INSERT INTO portal_modules_instances(control_key, view_file, friendly_name, module_id) VALUES('$name','$view_file','$name','$mid')");
			
			// Write file
			HModuleRobot::generateViewFile($name, $mid);			
			return true;
		}
		catch (Exception $ex) {
			return false;
			throw new Exception($ex->getMessage());
		}
	}
	
	function delete($id) {
		try {
			HSql::doQuery("DELETE FROM portal_modules_instances WHERE id = '$id'");
		}
		catch (Exception $ex) {
			return false;
		}
	}
}